package com.ihealthway.all.groupbuy.services;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.Daos;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.service.EntityService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Base service design for module server extends
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
public class BaseService<T> extends EntityService<T> {

    private static final Log logger = Logs.get();

    public BaseService() {
    }

    public BaseService(Dao dao) {
        super(dao);
    }

    public BaseService(Dao dao, Class<T> entityType) {
        super(dao, entityType);
    }

    /**
     * 依据单个列名获取数据
     * @param name    名称
     * @param value     键值
     * @return  实体数据
     */
    public T get(String name, Object value) {

        T get = null;

        try {
            List<T> list = dao().query(getEntityClass(), Cnd.where(name, "=", value));
            get = !Lang.isEmpty(list) ? list.get(0) : null;
        } catch (Exception e) {
            logger.errorf("%s 依据单个属性[%s -- %d]获取数据异常!!!",
                    getEntityClass().getSimpleName(), name, value);
            logger.error(e);
        }

        return get;
    }

    /**
     * EasyUI DataGrid 组件分页方法
     *
     * @param curPage   当前页码
     * @param pageSize  每页记录
     * @param cri       条件
     * @return  组件数据
     */
    public Map<String, Object> easyuiDGPager(Integer curPage, Integer pageSize, Criteria cri) {

        Map<String, Object> map = new HashMap<>();
        List<T> data = null;

        if (cri == null) {
            cri = Cnd.cri();
        }

        cri.where().and("data_status", "=", "0");
        Pager pager = null;
        if (curPage>0 && pageSize>0) {
            pager = dao().createPager(curPage, pageSize);
        }

        try {
            data = dao().query(getEntityClass(), cri, pager);
            map.put("rows", data);
        } catch (Exception e) {
            logger.errorf("%s 创建DataGrid分页数据异常!!!条件: %s", getEntityClass().getSimpleName(),
                    cri.toString());
            logger.error(e);
        }

        try {
            map.put("total", dao().count(getEntityClass(), cri));
        } catch (Exception e) {
            logger.errorf("%s 统计总记录数据时异常!!!", getEntityClass().getSimpleName());
            logger.error(e);
        }

        return map;
    }

    /**
     * EasyUI DataGrid 组件分页方法
     * @param sqlStatement SQL语句
     * @param curPage   当前页码
     * @param pageSize  每页记录
     * @param cri       条件
     * @param callback  自字义回调方法
     * @return  组件数据
     */
    public Map<String, Object> easyuiDGPagerWithFetch(String sqlStatement, Integer curPage, Integer pageSize, Criteria cri, SqlCallback callback) {

        Map<String, Object> data = new HashMap<>();

        List<T> rows = null;
        Pager pager = dao().createPager(curPage, pageSize);

        Sql sql = Sqls.queryRecord(sqlStatement);
        try {
            // read from https://nutz.cn/yvr/t/v101fe6uu2jo9o8egsp99ujjck
            sql.setPager(pager);
            sql.setCondition(cri);
            sql.setCallback(callback);
            dao().execute(sql);

            rows = sql.getList(getEntityClass());
        } catch (Exception e) {
            logger.errorf("Query %s create easyui data grid failed!!! Conditions: %s",
                    getEntityClass().getSimpleName(),
                    cri.toString());
            logger.error(e);
        }

        data.put("rows", rows);

        try {
            //TODO 如何处理动态条件下的别名操作
            data.put("total", Daos.queryCount(dao(), Sqls.create(sqlStatement).setCondition(cri)));
        } catch (Exception e) {
            logger.errorf("Count %s total items failed!!!", getEntityClass().getSimpleName());
            logger.error(e);
        }

        return data;
    }
}
